package com.jinhuhang.u2.myselfmodule.engine.invite;

import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;
import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.Invite;
import com.jinhuhang.u2.entity.InviteCode;
import com.jinhuhang.u2.entity.MyInvitation;
import com.jinhuhang.u2.myselfmodule.adapter.FriendListAdapter;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.customview.CustomToast;
import com.jinhuhang.u2.util.StringUtils;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import sun.misc.BASE64Encoder;

/**
 * Created by OnionMac on 17/9/24.
 */

public class InviteActivity extends ZSimpleBaseActivity {

    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.invite_code)
    LinearLayout mInviteCode;
    @Bind(R.id.invite_pcount)
    TextView mInvitePcount;
    @Bind(R.id.wechat)
    TextView mWechat;
    @Bind(R.id.wechat_favorite)
    TextView mWechatFavorite;
    @Bind(R.id.qqbtn)
    TextView mQqbtn;

    String url;
    @Bind(R.id.mycode)
    TextView mMycode;
    @Bind(R.id.friendLIst)
    RecyclerView mFriendLIst;
    @Bind(R.id.bglist)
    LinearLayout mBglist;
    @Bind(R.id.friendLIstlay)
    LinearLayout mFriendLIstlay;
    @Bind(R.id.myfriendcode)
    TextView mMyfriendcode;
    @Bind(R.id.codelay)
    LinearLayout mCodelay;
    @Bind(R.id.friendcode)
    EditText mFriendcode;
    private BASE64Encoder base64Encoder;
    FriendListAdapter mFriendListAdapter;

    List<MyInvitation> mMyInvitations = new ArrayList<>();
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "微博分享成功",
                            Toast.LENGTH_LONG).show();
                    break;

                case 2:
                    Toast.makeText(getApplicationContext(), "微信分享成功",
                            Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(), "朋友圈分享成功",
                            Toast.LENGTH_LONG).show();
                    break;
                case 4:
                    Toast.makeText(getApplicationContext(), "QQ分享成功",
                            Toast.LENGTH_LONG).show();
                    break;

                case 5:
                    Toast.makeText(getApplicationContext(), "取消分享",
                            Toast.LENGTH_LONG).show();
                    break;
                case 6:
                    Toast.makeText(getApplicationContext(), "分享失败!",
                            Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }

    };


    @Override
    protected void attachPre() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_invite;
    }

    @OnClick({R.id.wechat, R.id.wechat_favorite, R.id.qqbtn, R.id.toolbar_back, R.id.submit_share})
    void click(View view) {
        switch (view.getId()) {
            case R.id.wechat:
                shared1(Wechat.NAME);
                break;
            case R.id.wechat_favorite:
                shared1(WechatMoments.NAME);
                break;
            case R.id.qqbtn:
                shared1(QQ.NAME);
                break;
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.submit_share:
                setCode();
                break;
        }
    }

    @Override
    protected void initData() {
        super.initData();
        MobSDK.init(this,"1605f8d91ef52","04cd9093419eeb30f43600a87f7e5acb");
        mToolbarName.setText("邀请好友");
        mFriendListAdapter = new FriendListAdapter(R.layout.item_invite, mMyInvitations);
        mFriendLIst.setLayoutManager(new LinearLayoutManager(this));
        mFriendLIst.setAdapter(mFriendListAdapter);
        base64Encoder = new BASE64Encoder();
        getUrl();
        getCode();
        getList();
    }

    public void getUrl() {
        showDialog("");
        addSubscription(RetrofitUtils.getInstance().build()
                .userInvite(MainActivity.uid)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<Invite>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<Invite> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            url = data.getSingleData().address;
                            mMycode.setText(data.getSingleData().myInvitationCode);
                            mInvitePcount.setText(data.getSingleData().investUserAccount + "");
                        }
                        dissDialog();

                    }

                }));
    }

    public void setCode() {
        if (StringUtils.isEmpty(mFriendcode.getText().toString())){
            CustomToast.showToast("填写推荐人邀请码！");
        }
        showDialog("");
        addSubscription(RetrofitUtils.getInstance().build()
                .setInviteCode(MainActivity.uid, mFriendcode.getText().toString())
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<InviteCode>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<InviteCode> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            CustomToast.showToast("邀请成功！");
                         getCode();
                        }
                        else {

                        }
                        dissDialog();

                    }

                    @Override
                    protected void onFaild() {
                        super.onFaild();
                        dissDialog();
                    }
                }));
    }

    public void getCode() {
        showDialog("");
        addSubscription(RetrofitUtils.getInstance().build()
                .userInviteCode(MainActivity.uid)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<InviteCode>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<InviteCode> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            if (!StringUtils.isEmpty(data.getSingleData().getInvitationPhone())) {
                                mMyfriendcode.setText(data.getSingleData().getInvitationPhone());
                                mCodelay.setVisibility(View.VISIBLE);
                                mInviteCode.setVisibility(View.GONE);
                            } else {
                                mCodelay.setVisibility(View.GONE);
                                mInviteCode.setVisibility(View.VISIBLE);
                            }
                        }
                        dissDialog();
                    }
                }));
    }


    public void getList() {
        showDialog("");
        addSubscription(RetrofitUtils.getInstance().build()
                .friendList(MainActivity.uid, 1, 20)
                .compose(T.defaultScheduler())
                .subscribe(new ResultList<HttpWrapperList<MyInvitation>>() {

                    @Override
                    protected void onSuccess(HttpWrapperList<MyInvitation> data) {
                        if (data.code == Constant.SUCCESS_CODE) {
                            if (data.getData().size() > 0) {
                                mBglist.setVisibility(View.GONE);
                                mFriendLIstlay.setVisibility(View.VISIBLE);
                                mMyInvitations.addAll(data.getData());
                                mFriendListAdapter.notifyDataSetChanged();
                            } else {

                            }
                        }
                        dissDialog();
                    }

                }));
    }

    public void shareWechat(String name) {

        // 2、设置分享内容
        WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE); // 非常重要：一定要设置分享属性
        sp.setTitle("我已加入悠兔理财,一起来吧！"); // 分享标题
        sp.setText("理财就上悠兔理财，体验金好礼任性送，悠兔理财在您生活之余，给你快乐的财富..."); // 分享文本
        sp.setImageUrl("http://122.112.220.170:9008/jhh/sharesdkimg.jpg");// 网络图片rul
        Resources resources = getResources();
//		Bitmap  bitmap =  BitmapFactory.decodeResource(resources,R.drawable.shareu2);
//		sp.setImageData(bitmap);
        String userName = MyApplication.mSpUtil.getUser().getUserName();
        String content = url + "/" + base64Encoder.encode(userName.getBytes()) + "/" + MyApplication.mSpUtil.getUser().getUserId();
        sp.setUrl(content); // 网友点进链接后，可以看到分享的详情
        // 3、非常重要：获取平台对象
        Platform platForm = ShareSDK.getPlatform(name);


        platForm.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onCancel(Platform arg0, int arg1) {// 回调的地方是子线程，进行UI操作要用handle处理
                //   initStatus = true;
                handler.sendEmptyMessage(5);

            }

            @Override
            public void onComplete(Platform arg0, int arg1,
                                   HashMap<String, Object> arg2) {// 回调的地方是子线程，进行UI操作要用handle处理
                //   initStatus = true;
                if (arg0.getName().equals(Wechat.NAME)) {
                    handler.sendEmptyMessage(2);
                } else if (arg0.getName().equals(WechatMoments.NAME)) {
                    handler.sendEmptyMessage(3);
                } else if (arg0.getName().equals(QQ.NAME)) {
                    handler.sendEmptyMessage(4);
                }

            }

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {// 回调的地方是子线程，进行UI操作要用handle处理
                arg2.printStackTrace();
                //  initStatus = true;
                Message msg = new Message();
                msg.what = 6;
                msg.obj = arg2.getMessage();
                handler.sendMessage(msg);
            }

        }); // 设置分享事件回调
        platForm.share(sp);
    }
    public void shared(String name) {

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitleUrl(" ");
        sp.setText("nihao");
        sp.setTitle("标题");
//                sp.setShareType(Platform.SHARE_WEBPAGE);
//                sp.setUrl("www.mob.com");
       // sp.setImageUrl("http://f1.webshare.mob.com/dimgs/1c950a7b02087bf41bc56f07f7d3572c11dfcf36.jpg");
        sp.setImageUrl("http://122.112.220.170:9008/jhh/sharesdkimg.jpg");// 网络图片rul
        sp.setTitle("我已加入悠兔理财,一起来吧！"); // 分享标题
        sp.setText("理财就上悠兔理财，体验金好礼任性送，悠兔理财在您生活之余，给你快乐的财富...");
        String userName = MyApplication.mSpUtil.getUser().getUserName();
        String content = url + "/" + base64Encoder.encode(userName.getBytes()) + "/" + MyApplication.mSpUtil.getUser().getUserId();
        sp.setUrl(content); // 网友点进链接后，可以看到分享的详情
//                sp.setImageUrl("https://devfxchatimage.fx110.com/fxchatshare.png");
        Platform fb = ShareSDK.getPlatform (name);
// 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
        fb.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.i("1234","onComplete");
                if (platform.getName().equals(Wechat.NAME)) {
                    handler.sendEmptyMessage(2);
                } else if (platform.getName().equals(WechatMoments.NAME)) {
                    handler.sendEmptyMessage(3);
                } else if (platform.getName().equals(QQ.NAME)) {
                    handler.sendEmptyMessage(4);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("1234",throwable.toString());
                Message msg = new Message();
                msg.what = 6;
                msg.obj = throwable.getMessage();
                handler.sendMessage(msg);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.v("1234","onCancel");
                handler.sendEmptyMessage(5);
            }
        });
        fb.share(sp);
    }
    public void shared1(String name) {

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitleUrl("");
        sp.setShareType(Platform.SHARE_WEBPAGE);

        sp.setImageUrl("http://image.u2licai.com/jhh/sharesdkimg.jpg");// 网络图片rul
        sp.setTitle("我已加入悠兔理财,一起来吧！"); // 分享标题
        sp.setText("加入悠兔理财，好礼送不停，体验金好礼任性送，悠兔理财在您生活之余，给你快乐的财富...");
        String userName = MyApplication.mSpUtil.getUser().getUserName();
        String content = url + "/" + base64Encoder.encode(userName.getBytes()) + "/" + MyApplication.mSpUtil.getUser().getUserId();
        sp.setUrl(content); // 网友点进链接后，可以看到分享的详情
        if (name.equals(QQ.NAME)){
            sp.setTitleUrl(content);
        sp.setSite("我已加入悠兔理财,一起来吧！");
        sp.setSiteUrl("");
        }


        Platform fb = ShareSDK.getPlatform (name);
// 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
        fb.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.i("1234","onComplete");
                if (platform.getName().equals(Wechat.NAME)) {
                    handler.sendEmptyMessage(2);
                } else if (platform.getName().equals(WechatMoments.NAME)) {
                    handler.sendEmptyMessage(3);
                } else if (platform.getName().equals(QQ.NAME)) {
                    handler.sendEmptyMessage(4);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("1234",throwable.toString());
                Message msg = new Message();
                msg.what = 6;
                msg.obj = throwable.getMessage();
                handler.sendMessage(msg);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.v("1234","onCancel");
                handler.sendEmptyMessage(5);
            }
        });
        fb.share(sp);
    }
}
